package com.jic.market.common.util;


import org.apache.commons.beanutils.PropertyUtils;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.*;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mj
 * @date: 2020年01月10日
 */
public class Collections3 {
    private static Logger log = LoggerFactory.getLogger(Collections3.class);

    public Collections3() {
    }

    public static <K, T> Map<K, List<T>> partitionByProperty(Collection<T> collection, String propertyName) {
        if (!CollectionUtils.isEmpty(collection) && !StringUtils.isEmpty(propertyName)) {
            final Map<K, List<T>> map = Maps.newHashMap();
            Iterator var3 = collection.iterator();

            while(var3.hasNext()) {
                T obj = (T) var3.next();
                if (obj != null) {
                    try {
                        final K key = (K) PropertyUtils.getProperty(obj, propertyName);
                        List<T> items = (List)Optional.fromNullable(map.get(key)).or(new Supplier<List<T>>() {
                            public List<T> get() {
                                List<T> items = Lists.newArrayList();
                                map.put(key, items);
                                return items;
                            }
                        });
                        items.add(obj);
                    } catch (IllegalAccessException | NoSuchMethodException var7) {
                        log.error("partition collection By property[" + propertyName + "]error, will break", var7);
                        break;
                    } catch (Exception var8) {
                        log.warn("get property[" + propertyName + "]from obj error, skip this obj", var8);
                    }
                }
            }

            return map;
        } else {
            return Collections.emptyMap();
        }
    }
    public static List extractToList(Collection collection, String propertyName) {
        if (CollectionUtils.isEmpty(collection)) {
            return null;
        } else {
            ArrayList list = new ArrayList(collection.size());

            try {
                Iterator var3 = collection.iterator();

                while(var3.hasNext()) {
                    Object obj = var3.next();
                    list.add(PropertyUtils.getProperty(obj, propertyName));
                }

                return list;
            } catch (Exception var5) {
                throw new RuntimeException(var5);
            }
        }
    }


}
